package pcmd_dir_base;

use strict;
use warnings;

use File::Spec;
use File::Basename;

#-------
# New --
#-------
sub new {
    my $arg0 = shift;
    my $cls = ref($arg0) || $arg0;
    
    my $self = {};
    bless $self, $cls;
    
    $self->init(@_);
    
    return $self;
}


#--------------
# Init class --
#--------------
sub init {
    my $self = shift;
    my $parent = shift;
    my $path = shift;
    
    # Store parent
    $self->{parent} = $parent;

    # Store path and get content of the directory
    $self->{path} = $path;
    
    # Get list of files amd directories
    my @paths = $self->get_file_paths();
    
    # File hash
    $self->{files} = {};

    # Updir
    if ($self->{parent}->get_root_dir() ne $path) {
        my $updir = File::Spec->updir();
        $self->{files}{$updir} = pcmd_item->new( {
            'abs_path'      => File::Spec->catdir($path, $updir),
            'name'          => $updir,
            'type'          => 'dir',
            'ext'           => '<DIR>',
        });
    };

    # Get items
    foreach my $abs_path (@paths) {    
        $self->add($abs_path);
    };
};


#-------------
# Get files --
#-------------
sub get_files {
    my $self = shift;
    my $base = shift;

    my @tmp = sort {$a->compare($b, $base)} values %{$self->{'files'}};

    return \@tmp;
};


#-------
# Add --
#-------
sub add {
    my $self = shift;
    my $abs_path = shift;    
    
    if (-d $abs_path) {
        $self->add_dir($abs_path);
    } else {
        $self->add_file($abs_path);
    };     
};

#-----------------
# Add directory --
#-----------------
sub add_dir {
    my $self = shift;
    my $abs_path = shift;
    
    my ($name, $directories, $ext) = fileparse($abs_path);
    
    my $file = pcmd_item->new( {
        'abs_path'      => $abs_path,
        'name'          => $name,
        'type'          => 'dir',
        'ext'           => '<DIR>',
    });
    
    $self->{files}{$name} = $file;
};


#------------
# Add file --
#------------
sub add_file {
    my $self = shift;
    my $abs_path = shift;
    
    my ($name, $directories, $ext) = fileparse($abs_path, qr/\.[^.]*/);
    
    my $file = pcmd_item->new( {
        'abs_path'      => $abs_path,
        'name'          => $name,
        'type'          => 'file',
        'ext'           => $ext,
    });

    $self->{files}{$name . $ext} = $file;;
};


#----------
# Remove --
#----------
sub remove {
    my $self = shift;
    my $name = shift;

    delete $self->{files}{$name};
};


#------------
# Get path --
#------------
sub get_path {
    my $self = shift;
   
    return $self->{path};
};


#------------------------------------------
# Get file paths - Should be overwritten --
#------------------------------------------
sub get_file_paths {

    return ();
};

1;

